package com.zbkj.crmeb.store.service.impl;

import cn.hutool.core.util.StrUtil;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.factory.TaskProcessEngineFactory;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taobao.pac.sdk.cp.dataobject.request.MODUAN_ORDER_CREATE.request;
import com.taobao.pac.sdk.cp.dataobject.response.MODUAN_ORDER_CREATE.response;
import com.utils.DateUtil;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelActivity;
import com.zbkj.crmeb.chant.service.ChannelActivityService;
import com.zbkj.crmeb.enums.ChannelGroupBookingActivityStatusEnum;
import com.zbkj.crmeb.enums.CommissionTypeEnum;
import com.zbkj.crmeb.front.request.IndexStoreProductSearchRequest;
import com.zbkj.crmeb.front.response.ProductResponse;
import com.zbkj.crmeb.merchant.admin.service.MerStoreProductService;
import com.zbkj.crmeb.merchant.admin.service.StoreProductStockService;
import com.zbkj.crmeb.merchant.api.service.MerProductService;
import com.zbkj.crmeb.store.dao.ChannelGroupBookingDao;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.request.ChannelGroupBookingRequest;
import com.zbkj.crmeb.store.response.*;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.task.plat.PushProductTask;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.ls.LSInput;


import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;

@Service
@Slf4j
public class ChannelGroupBookingServiceImpl extends ServiceImpl<ChannelGroupBookingDao, ChannelGroupBooking> implements ChannelGroupBookingService {

    @Autowired
    private StoreProductGroupActivityService storeProductGroupActivityService;
    @Autowired
    private MerProductService productService;
    @Autowired
    private MerStoreProductService merStoreProductService;
    @Autowired
    private StoreProductStockService storeProductStockService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private UserService userService;
    @Autowired
    private ChannelActivityService channelActivityService;
    @Autowired
    private StoreProductActivityService storeProductActivityService;
    @Autowired
    private StoreProductDescriptionService productDescriptionService;

    @Resource
    private Redisson redisson;
    private static final String LOCK_KEY = ChannelGroupBookingServiceImpl.class.getName();


    /**
     * 功能描述: 新增/修改拼团信息
     *
     * @Param: [request, merId]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2022/11/29 15:05
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdateActivity(ChannelGroupBookingRequest request, Integer merId) {
//        RLock rLock = redisson.getLock(LOCK_KEY);
//        boolean result = false;
//        try {
//            if (!rLock.tryLock(3, TimeUnit.SECONDS)){
//                log.warn("未获取到锁，稍后尝试");
//                throw new CrmebException("其他用户正在创建拼团活动，请稍后重试");
//            }
//            log.error("获取到锁");
//            result = saveOrUpdateGroupActivity( request, merId);
//        }catch (Exception e){
//            log.error("执行失败,{}", e.fillInStackTrace());
//            throw new CrmebException(e.getMessage() == null ? e.fillInStackTrace().toString() : e.getMessage());
//        }finally {
//            // 解锁
//            rLock.unlock();
//        }
//        return result;
        // 允许拼团活动里的商品库存为空或者0
        try {
            List<ChannelGroupBookingRequest.StoreProductGroupActivityRequest> list = new ArrayList<>();
            list = request.getStoreProductGroupActivities().stream().map(item -> {
                if (item != null && CollectionUtils.isNotEmpty(item.getSkuPrices())) {
                    item.getSkuPrices().stream().forEach(q -> {
                        if (q != null && q.getStock() == null) {
                            // 设置库存初始值0
                            q.setStock(0);
                        }
                    });
                }
                return item;
            }).collect(Collectors.toList());
            request.setStoreProductGroupActivities(list);
        }catch (Exception e){
            log.error("设置库存初始值0错误");
        }
        return saveOrUpdateGroupActivity(request, merId);

    }

    private boolean saveOrUpdateGroupActivity(ChannelGroupBookingRequest request, Integer merId) {

        //商家进行中的限时活动
        List<ChannelActivity> channelActivities = channelActivityService.list(Wrappers.<ChannelActivity>lambdaQuery()
                .lt(ChannelActivity::getStartTime, new Date())
                .gt(ChannelActivity::getEndTime, new Date())
                .eq(ChannelActivity::getMerId, merId)
                .eq(ChannelActivity::getIsDel, 0));
        if (CollectionUtils.isNotEmpty(channelActivities)){
            List<Integer> spikeActivityIds = channelActivities.stream().map(ChannelActivity::getId).collect(Collectors.toList());
            List<StoreProductActivity> list = storeProductActivityService.list(Wrappers.<StoreProductActivity>lambdaQuery()
                    .in(StoreProductActivity::getActivityId, spikeActivityIds));
            // 收集商品id
            if (CollectionUtils.isNotEmpty(list)){
                List<Integer> spikeActivityProductIds = list.stream().map(StoreProductActivity::getProductId).collect(Collectors.toList());
                if (spikeActivityProductIds.contains(request.getProductId())){
                    throw new CrmebException("该商品已参加限时活动，暂时不能参与拼团活动");
                }
            }
        }

        //活动时间为时间段时
        if (request.getActivityTimeType() == 1) {
            if (StringUtils.isBlank(request.getActivityStartTime()) || StringUtils.isBlank(request.getActivityEndTime())) {
                throw new CrmebException("时间不能为空");
            }
            if (DateUtil.strToDate(request.getActivityStartTime(), Constants.DATE_FORMAT).after(DateUtil.strToDate(request.getActivityEndTime(), Constants.DATE_FORMAT))) {
                throw new CrmebException("开始时间必须小于结束时间！");
            }
        }

        //有限购时，判断限购数量是否为空
        if (request.getPurchaseLimitType() == 1) {
            if (Objects.isNull(request.getPurchaseLimitNumber())) {
                throw new CrmebException("限购数量不能为空！");
            }
        }

        //修改时判断是否修改商品
        List<Integer> activityIds = null;
        //参团人数与id对应关系 修改阶梯拼团时使用
        Map<Integer, Integer> numberToId = new HashMap<>();
        if (Objects.nonNull(request.getId())) {
            ChannelGroupBooking one = this.getById(request.getId());
            if (Objects.isNull(one)) {
                throw new CrmebException("活动不存在！");
            }
            //查询是否是阶梯拼团
            activityIds = storeProductGroupActivityService.getActivityIdsByActivityId(request.getId(), getActivityIds(merId), request.getGroupId());
            //该拼团活动下商品id
            Integer productId = storeProductGroupActivityService.getProductIdByActivityId(request.getId());
            //判断是否修改商品，修改商品时，删除子表之前商品的数据
            if (!Objects.equals(request.getProductId(), productId)) {
//                storeProductGroupActivityService.removeProductByProductId(productId);
                // 校验新商品的拼团库存量是否超过商品库存量 并且 锁定拼团库存
                storeProductStockService.checkStock(request);
                // 修改商品时，归还原商品锁定的库存
                storeProductStockService.returnStock(productId, request, getActivityIds(merId));

            }else{
                // 没有修改商品，则校验新的库存量是否超过商品剩余可用库存量
                storeProductStockService.checkNewStock(request, getActivityIds(merId));

            }
            numberToId = this.list(Wrappers.<ChannelGroupBooking>lambdaQuery().in(ChannelGroupBooking::getId, activityIds)).stream().collect(Collectors.toMap(ChannelGroupBooking::getJoinPersonNumber, ChannelGroupBooking::getId, (v1, v2) -> v2));

        } else {
            //新增时，判断商品是否有参加拼团活动
            //查询商品是否参加其他拼团活动
//            if (storeProductGroupActivityService.getProductInfoIsExistByProductId(request.getProductId(), getActivityIds(merId))) {
//                throw new CrmebException("商品已有拼团活动");
//            }

            // 校验新商品的拼团库存量是否超过商品库存量
            storeProductStockService.checkStock(request);

        }

        //判断拼团价是否小于售价
        StoreProductResponse productInfo = merStoreProductService.getByProductId(request.getProductId(), merId, false, false, null, false);
        //sku对应价格
        Map<String, BigDecimal> map = productInfo.getAttrValue().stream()
                .collect(Collectors.toMap(
                        StoreProductAttrValueResponse::getSourceSkuId,
                        value -> value.getPrice().add(value.getTaxAndSecondPrice())
                ));
        for (ChannelGroupBookingRequest.StoreProductGroupActivityRequest storeProductGroupActivityRequest : request.getStoreProductGroupActivities()){
            for (ChannelGroupBookingRequest.StoreProductGroupActivityRequest.StoreProductGroupPriceRequest storeProductGroupPriceRequest : storeProductGroupActivityRequest.getSkuPrices()){
                //零售价
                BigDecimal otPrice = map.get(storeProductGroupPriceRequest.getSourceSkuId());
                //零售价小于设置的拼团价
                if (otPrice.compareTo(storeProductGroupPriceRequest.getPackagePrice()) < 0){
                    throw new CrmebException("拼团价格必须小于客户成交价格");
                }
            }
        }
        String groupId = null;
        if(StringUtils.isEmpty(request.getGroupId())){
            groupId = UUID.randomUUID().toString().replace("-", "");
        }else{
            groupId = request.getGroupId();
        }
        List<ChannelGroupBooking> channelGroupBookings = new ArrayList<>();
        //拼团人数与拼团价对应关系
        List<ChannelGroupBookingRequest.StoreProductGroupActivityRequest> storeProductGroupActivities = request.getStoreProductGroupActivities();
        //遍历拼团人数，存入主表
        //阶梯拼团存入逻辑为多个多人拼团
        for (ChannelGroupBookingRequest.StoreProductGroupActivityRequest activityRequest : storeProductGroupActivities) {
            ChannelGroupBooking channelGroupBooking = new ChannelGroupBooking();
            BeanUtils.copyProperties(request, channelGroupBooking);
            channelGroupBooking.setMerId(merId);
            channelGroupBooking.setJoinPersonNumber(activityRequest.getJoinPersonNumber());
            if (storeProductGroupActivities.size() == 1){
                channelGroupBooking.setId(request.getId());
            } else {
                channelGroupBooking.setId(numberToId.get(activityRequest.getJoinPersonNumber()));
            }
            if (request.getActivityTimeType() == 1) {
                channelGroupBooking.setActivityStartTime(DateUtil.strToDate(request.getActivityStartTime(), Constants.DATE_FORMAT));
                channelGroupBooking.setActivityEndTime(DateUtil.strToDate(request.getActivityEndTime(), Constants.DATE_FORMAT));
            } else {
                channelGroupBooking.setActivityStartTime(null);
                channelGroupBooking.setActivityEndTime(null);
            }
            if (request.getPurchaseLimitType() == 0){
                channelGroupBooking.setPurchaseLimitNumber(null);
            }
            channelGroupBooking.setCreateTime(new Date());
            if(StringUtils.isEmpty(channelGroupBooking.getGroupId())){
                channelGroupBooking.setGroupId(groupId);
            }

            channelGroupBookings.add(channelGroupBooking);
        }
        //获取主键id
        boolean saveGroup = this.saveOrUpdateBatch(channelGroupBookings);

        //修改时判断阶梯拼团是否删除一个阶梯
        if (Objects.nonNull(request.getId())){
            List<Integer> ids = activityIds;
            if(CollectionUtils.isEmpty(ids)) {
                ids = storeProductGroupActivityService.getActivityIdsByActivityId(request.getId(), getActivityIds(merId), request.getGroupId());
            }
            for (ChannelGroupBooking channelGroupBooking : channelGroupBookings){
                ids.remove(channelGroupBooking.getId());
            }
            for (Integer id : ids){
                this.removeById(id);
                storeProductGroupActivityService.removeProductByActivityId(Arrays.asList(id));
            }
        }

        //存储子表数据
        List<StoreProductGroupActivity> storeProductGroupActivityList = new ArrayList<>();
        //人数对应的主键id
        numberToId = channelGroupBookings.stream().collect(Collectors.toMap(ChannelGroupBooking::getJoinPersonNumber, ChannelGroupBooking::getId));
        for (ChannelGroupBookingRequest.StoreProductGroupActivityRequest activityRequest : storeProductGroupActivities) {
            for (ChannelGroupBookingRequest.StoreProductGroupActivityRequest.StoreProductGroupPriceRequest priceRequest : activityRequest.getSkuPrices()) {
                StoreProductGroupActivity storeProductGroupActivity = new StoreProductGroupActivity();
                storeProductGroupActivity.setActivityId(numberToId.get(activityRequest.getJoinPersonNumber()))
                        .setProductId(request.getProductId())
                        .setSourceSkuId(priceRequest.getSourceSkuId())
                        .setStock(priceRequest.getStock())
                        .setPackagePrice(priceRequest.getPackagePrice())
                        .setId(priceRequest.getId());
                if (Objects.isNull(priceRequest.getId())) {
                    storeProductGroupActivity.setCreateTime(new Date());
                }
                if(StringUtils.isEmpty(storeProductGroupActivity.getGroupId())){
                    storeProductGroupActivity.setGroupId(groupId);
                }
                storeProductGroupActivityList.add(storeProductGroupActivity);
            }
        }
        boolean savePrice = storeProductGroupActivityService.saveOrUpdateBatch(storeProductGroupActivityList);
        return saveGroup && savePrice;
    }

    /**
     * 功能描述: 通过活动id设置活动排序
     *
     * @Param: [activityId, sort]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2022/11/29 15:24
     */
    @Override
    public Boolean setActivitySort(Integer activityId, Integer sort) {
        return this.update(Wrappers.<ChannelGroupBooking>lambdaUpdate()
                .eq(ChannelGroupBooking::getId, activityId)
                .set(ChannelGroupBooking::getSort, sort));
    }

    /**
     * 功能描述: 获取拼团活动列表
     *
     * @Param: [activityName, activityStatus, request, merId]
     * @Return: com.github.pagehelper.PageInfo<com.zbkj.crmeb.store.response.ChannelGroupBookingResponse>
     * @Author: wangzh
     * @Date: 2022/11/29 17:30
     */
    @Override
    public PageInfo<ChannelGroupBookingResponse> getList(String activityName, Integer activityStatus, String leaderName, PageParamRequest request, Integer merId, String productName) {
        List<ChannelGroupBookingResponse> responses = new ArrayList<>();
        LambdaQueryWrapper<ChannelGroupBooking> queryWrapper = new LambdaQueryWrapper<>();
        List<ChannelGroupBooking> list1 = this.list(Wrappers.<ChannelGroupBooking>lambdaQuery().eq(ChannelGroupBooking::getMerId, merId));
        if (CollectionUtils.isEmpty(list1)){
            return new PageInfo<ChannelGroupBookingResponse>();
        }
        List<Integer> activityIds1 = list1.stream().map(ChannelGroupBooking::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(activityIds1)) {
            return new PageInfo<ChannelGroupBookingResponse>();
        }
        List<Integer> productIdList = new ArrayList<>();
        if(StringUtils.isNotEmpty(productName)){
            //商品id集合
            productIdList = storeProductService.listProductIdByStoreName(productName);

        }
        //阶梯拼团算多个多人拼团，但是每个拼团只可添加一个商品，所以使用商品表通过商品id分组获取拼团id，排除阶梯拼团查出来许多信息
        List<StoreProductGroupActivity> storeProductGroupActivities = storeProductGroupActivityService.getActivityId(activityIds1, productIdList);
        List<Integer> ids = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(storeProductGroupActivities)) {
            ids = storeProductGroupActivities.stream().map(StoreProductGroupActivity::getActivityId).collect(Collectors.toList());
        }
        //当前商户下的拼团活动
        queryWrapper.eq(ChannelGroupBooking::getMerId, merId)
                .in(CollectionUtils.isNotEmpty(ids), ChannelGroupBooking::getId, ids);
        //模糊查询活动名称
        if (StringUtils.isNotBlank(activityName)) {
            queryWrapper.like(ChannelGroupBooking::getActivityName, activityName);
        }
        // 模糊查询团长名字
        queryWrapper.like(StringUtils.isNotBlank(leaderName), ChannelGroupBooking::getLeaderName, leaderName);

        //活动状态查询
        if (Objects.nonNull(activityStatus)) {
            switch (ChannelGroupBookingActivityStatusEnum.valueOf(activityStatus)) {
                case NOT_STARTED:
                    queryWrapper.gt(ChannelGroupBooking::getActivityStartTime, new Date());
                    break;
                case IN_PROGRESS:
                    // 开始时间小于当前时间 结束时间大于当前时间
                    // 长期有效活动是否提前结束
                    queryWrapper.and(e -> e.lt(ChannelGroupBooking::getActivityStartTime, new Date())
                            .gt(ChannelGroupBooking::getActivityEndTime, new Date())
                            .or(i -> i.eq(ChannelGroupBooking::getActivityTimeType, 0)
                                    .isNull(ChannelGroupBooking::getActivityEndTime)));
                    break;
                case END:
                    queryWrapper.lt(ChannelGroupBooking::getActivityEndTime, new Date());
                default:
                    break;
            }
        }
        queryWrapper.orderByAsc(ChannelGroupBooking::getSort);
        //查询活动信息
        Page<Object> pageInfo = PageHelper.startPage(request.getPage(), request.getLimit());
        List<ChannelGroupBooking> list = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return CommonPage.copyPageInfo(pageInfo, new ArrayList<>());
        }

        //团长id集合
        List<Integer> leaderIds = list.stream().map(ChannelGroupBooking::getLeaderId).distinct().collect(Collectors.toList());
        List<User> leaderList = userService.list(Wrappers.<User>lambdaQuery().in(User::getUid, leaderIds));
        //团长map
        Map<Integer, User> leaderMap = leaderList.stream().collect(Collectors.toMap(User::getUid, e -> e));

        //活动id列表
        List<Integer> activityIds = list.stream().map(ChannelGroupBooking::getId).collect(Collectors.toList());
        List<StoreProductGroupActivity> storeProductGroupActivityList = storeProductGroupActivityService.getByActivityIds(activityIds);
        Map<Integer, StoreProductGroupActivity> map = storeProductGroupActivityList.stream().collect(Collectors.toMap(StoreProductGroupActivity::getActivityId, e -> e));
        //商品id集合
        List<Integer> productIds = storeProductGroupActivityList.stream().map(StoreProductGroupActivity::getProductId).distinct().collect(Collectors.toList());
        List<StoreProduct> productList = storeProductService.getListInIds(productIds);
        //商品id对应的商品详情
        Map<Integer, StoreProduct> productMap = productList.stream().collect(Collectors.toMap(StoreProduct::getId, e -> e));
        for (ChannelGroupBooking channelGroupBooking : list) {
            StoreProductGroupActivity storeProductGroupActivity = map.get(channelGroupBooking.getId());
            ChannelGroupBookingResponse response = new ChannelGroupBookingResponse();
            response.setId(channelGroupBooking.getId())
                    .setGroupId(channelGroupBooking.getGroupId())
                    .setSort(channelGroupBooking.getSort())
                    .setActivityName(channelGroupBooking.getActivityName())
                    .setProductId(storeProductGroupActivity.getProductId())
                    .setPackagePrice(storeProductGroupActivity.getPackagePrice());

            setBookingStatus(channelGroupBooking, response);

            //设置商品名称
            response.setProductName(productMap.get(storeProductGroupActivity.getProductId()).getStoreName());
            //设置团长名称
            log.info("设置团长名称:{},{},{}", JSONObject.toJSONString(leaderMap), JSONObject.toJSONString(channelGroupBooking), JSONObject.toJSONString(leaderMap.get(channelGroupBooking.getLeaderId())));
            if(null != leaderMap && null != channelGroupBooking.getLeaderId() && null != leaderMap.get(channelGroupBooking.getLeaderId())) {
                response.setLeaderName(leaderMap.get(channelGroupBooking.getLeaderId()).getNickname());
            }
            responses.add(response);
        }

        return CommonPage.copyPageInfo(pageInfo, responses);
    }

    private void setBookingStatus(ChannelGroupBooking channelGroupBooking, ChannelGroupBookingResponse response){
        //设置活动状态
        if (channelGroupBooking.getActivityTimeType() == 0) {
            response.setActivityTimeType("长期有效");
            response.setActivityStatus(ChannelGroupBookingActivityStatusEnum.IN_PROGRESS.getMsg());
            if (Objects.nonNull(channelGroupBooking.getActivityEndTime())){
                SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT);
                response.setActivityTimeType(StrUtil.format("长期有效，于 {} 提前结束", sdf.format(channelGroupBooking.getActivityEndTime())));
                response.setActivityStatus(ChannelGroupBookingActivityStatusEnum.END.getMsg());
            }
        } else if (channelGroupBooking.getActivityStartTime().after(new Date())) {
            response.setActivityTimeType("活动时间段");
            response.setActivityStartTime(DateUtil.dateToStr(channelGroupBooking.getActivityStartTime(), Constants.DATE_FORMAT));
            response.setActivityEndTime(DateUtil.dateToStr(channelGroupBooking.getActivityEndTime(), Constants.DATE_FORMAT));
            response.setActivityStatus(ChannelGroupBookingActivityStatusEnum.NOT_STARTED.getMsg());
        } else if (channelGroupBooking.getActivityEndTime().before(new Date())) {
            response.setActivityTimeType("活动时间段");
            response.setActivityStartTime(DateUtil.dateToStr(channelGroupBooking.getActivityStartTime(), Constants.DATE_FORMAT));
            response.setActivityEndTime(DateUtil.dateToStr(channelGroupBooking.getActivityEndTime(), Constants.DATE_FORMAT));
            response.setActivityStatus(ChannelGroupBookingActivityStatusEnum.END.getMsg());
        } else {
            response.setActivityTimeType("活动时间段");
            response.setActivityStartTime(DateUtil.dateToStr(channelGroupBooking.getActivityStartTime(), Constants.DATE_FORMAT));
            response.setActivityEndTime(DateUtil.dateToStr(channelGroupBooking.getActivityEndTime(), Constants.DATE_FORMAT));
            response.setActivityStatus(ChannelGroupBookingActivityStatusEnum.IN_PROGRESS.getMsg());
        }
    }

    /**
     * 功能描述: 根据id查询拼团信息
     *
     * @Param: [id]
     * @Return: com.zbkj.crmeb.store.response.ChannelGroupBookingResponse
     * @Author: wangzh
     * @Date: 2022/11/30 9:52
     */
    @Override
    public ChannelGroupBookingResponse getByActivityId(Integer id, Integer merId) {
        ChannelGroupBookingResponse response = new ChannelGroupBookingResponse();
        // 根据 ActivityId 获取 groupId
        String groupId = storeProductGroupActivityService.getGroupIdByActivityId(id);
        List<Integer> activityIds = storeProductGroupActivityService.getActivityIdsByActivityId(id, getActivityIds(merId), groupId);
        //多人拼团 /阶梯拼团信息查询
        List<ChannelGroupBooking> channelGroupBookings = this.list(Wrappers.<ChannelGroupBooking>lambdaQuery().in(ChannelGroupBooking::getId, activityIds));
        if (CollectionUtils.isEmpty(channelGroupBookings)){
            return response;
        }

        Integer productId = storeProductGroupActivityService.getProductIdByActivityId(channelGroupBookings.get(0).getId());
        response.setProductId(productId);
        List<Integer> joinPersonNumber = channelGroupBookings.stream().map(ChannelGroupBooking::getJoinPersonNumber).collect(Collectors.toList());
        //阶梯拼团 活动信息都相同，只有商品价格不同
        ChannelGroupBooking channelGroupBooking = channelGroupBookings.get(0);
        BeanUtils.copyProperties(channelGroupBooking, response);
        //阶梯拼团时，拼团人数会有多个
        response.setJoinPersonNumber(joinPersonNumber);
        if (channelGroupBooking.getActivityTimeType() == 0) {
            response.setActivityTimeType("长期有效");
        } else if (channelGroupBooking.getActivityTimeType() == 1) {
            response.setActivityTimeType("活动时间段");
            response.setActivityStartTime(DateUtil.dateToStr(channelGroupBooking.getActivityStartTime(), Constants.DATE_FORMAT));
            response.setActivityEndTime(DateUtil.dateToStr(channelGroupBooking.getActivityEndTime(), Constants.DATE_FORMAT));
        }
        return response;
    }

    /**
     * 功能描述: 根据商品id获取拼团商品详情
     *
     * @Param: [productId]
     * @Return: com.zbkj.crmeb.store.response.StoreProductGroupActivityResponse
     * @Author: wangzh
     * @Date: 2022/11/30 14:19
     */
    @Override
    public StoreProductGroupActivityResponse getProductInfoByProductId(Integer productId, Integer merId, Boolean isApp, String groupId ) {
        List<Integer> ids = getActivityIds(merId);
        StoreProductResponse storeProduct;
        //小程序访问
        if (isApp){
            //活动已结束，商品不再属于拼团商品，不应该让商品详情再返回
            if (!getActivityIsUnderwayByProductId(productId, getInProgressActivityIds(merId))){
                return null;
            }
            //获取拼团活动下商品
            ids = getInProgressActivityIds(merId);
            if (CollectionUtils.isEmpty(ids)){
                return null;
            }
            storeProduct = merStoreProductService.getByProductId(productId, merId, true, true, null, false);
        } else {
            storeProduct = storeProductService.getByProductId(productId);
        }

        List<StoreProductAttrValueResponse> attrValue = storeProduct.getAttrValue();
        Map<String, StoreProductAttrValueResponse> attrValueResponseMap = attrValue.stream().collect(Collectors.toMap(StoreProductAttrValueResponse::getSourceSkuId, e -> e));
        StoreProductGroupActivityResponse response = new StoreProductGroupActivityResponse();
        response.setProductId(productId)
                .setImage(storeProduct.getImage())
                .setProductName(storeProduct.getStoreName())
                .setProductPrice(storeProduct.getPrice())
                .setStock(storeProduct.getStock());

        List<StoreProductGroupActivity> groupActivityList = storeProductGroupActivityService.getProductInfoByproductId(productId, ids, groupId);
        if (CollectionUtils.isEmpty(groupActivityList)) {
            return null;
        }
        List<StoreProductGroupActivityResponse.StoreProductGroupPriceResponse> storeProductGroupPriceResponses = new ArrayList<>();
        List<Integer> activityIds = groupActivityList.stream().map(StoreProductGroupActivity::getActivityId).distinct().collect(Collectors.toList());
        List<ChannelGroupBooking> channelGroupBookings = getGroupBookingInfoInIds(activityIds);

        for (ChannelGroupBooking channelGroupBooking : channelGroupBookings) {
            //参团人数
            Integer joinPersonNumber = channelGroupBooking.getJoinPersonNumber();
            StoreProductGroupActivityResponse.StoreProductGroupPriceResponse storeProductGroupPriceResponse = new StoreProductGroupActivityResponse.StoreProductGroupPriceResponse();
            storeProductGroupPriceResponse.setJoinPersonNumber(joinPersonNumber);
            List<StoreProductGroupActivityResponse.StoreProductGroupPriceResponse.SkuPrice> skuPrices = new ArrayList<>();
            for (StoreProductGroupActivity storeProductGroupActivity : groupActivityList) {
                //sku属性设置
                StoreProductAttrValueResponse storeProductAttrValueResponse = attrValueResponseMap.get(storeProductGroupActivity.getSourceSkuId());
                if (Objects.equals(storeProductGroupActivity.getActivityId(), channelGroupBooking.getId())) {
                    StoreProductGroupActivityResponse.StoreProductGroupPriceResponse.SkuPrice skuPrice = new StoreProductGroupActivityResponse.StoreProductGroupPriceResponse.SkuPrice();
                    Integer stock = 0;
                    if(storeProductGroupActivity.getStock() != null){
                        stock = storeProductGroupActivity.getStock();
                    }else {
                        stock = storeProductAttrValueResponse.getStock();
                    }
                    skuPrice.setId(storeProductGroupActivity.getId())
                            .setSourceSkuId(storeProductGroupActivity.getSourceSkuId())
                            .setSku(storeProductAttrValueResponse.getSuk())
                            .setUseStock(storeProductAttrValueResponse.getStock())
                            .setStock(stock)
                            .setPrice(storeProductAttrValueResponse.getPrice())
                            .setPackagePrice(storeProductGroupActivity.getPackagePrice())
                            .setGroupStock(storeProductGroupActivity.getStock())
                            .setImage(storeProductAttrValueResponse.getImage());
                    skuPrices.add(skuPrice);
                }
            }
            //设置 拼团人数对应规格价格
            storeProductGroupPriceResponse.setSkuPrices(skuPrices);
            storeProductGroupPriceResponses.add(storeProductGroupPriceResponse);
        }
        if(channelGroupBookings.get(0).getLeaderId() != null && channelGroupBookings.get(0).getLeaderId() != 0){
            response.setLeaderId(channelGroupBookings.get(0).getLeaderId());
        }
        response.setStoreProductGroupPriceResponses(storeProductGroupPriceResponses);
        return response;
    }

    /**
     * 功能描述: 通过id集合获取拼团信息
     *
     * @Param: [ids]
     * @Return: java.util.List<com.zbkj.crmeb.store.model.ChannelGroupBooking>
     * @Author: wangzh
     * @Date: 2022/11/30 14:20
     */
    @Override
    public List<ChannelGroupBooking> getGroupBookingInfoInIds(List<Integer> ids) {
        return this.list(Wrappers.<ChannelGroupBooking>lambdaQuery()
                .in(CollectionUtils.isNotEmpty(ids), ChannelGroupBooking::getId, ids)
                .groupBy(ChannelGroupBooking::getJoinPersonNumber));
    }

    /**
     * 功能描述: 删除活动信息与活动商品
     * @Param: [activityId]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2022/11/30 15:36
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeActivityByActivityId(Integer activityId, Integer merId) {
        // 根据 ActivityId 获取 groupId
        String groupId = storeProductGroupActivityService.getGroupIdByActivityId(activityId);
        List<Integer> activityIds = storeProductGroupActivityService.getActivityIdsByActivityId(activityId, getActivityIds(merId), groupId);
        // 归还库存
        ChannelGroupBooking groupBooking = this.getOne(Wrappers.<ChannelGroupBooking>lambdaQuery().in(ChannelGroupBooking::getGroupId, groupId).last("limit 1"));
        String logID = UUID.randomUUID().toString();
        log.info("logID:[{}]", logID);
        storeProductStockService.returnStockForActivityFinish(groupBooking,getActivityIds(merId), logID);
        return this.removeByIds(activityIds) && storeProductGroupActivityService.removeProductByActivityId(activityIds);
    }

    /**
     * 功能描述: 提前结束拼团活动
     * @Param: [activityId]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2022/12/1 16:53
     */
    @Override
    public Boolean earlyTerminationActivity(Integer activityId, Integer merId) {
        // 根据 ActivityId 获取 groupId
        String groupId = storeProductGroupActivityService.getGroupIdByActivityId(activityId);
        return this.update(Wrappers.<ChannelGroupBooking>lambdaUpdate()
                .in(ChannelGroupBooking::getId, storeProductGroupActivityService.getActivityIdsByActivityId(activityId, getActivityIds(merId), groupId))
                .set(ChannelGroupBooking::getActivityEndTime, new Date()));
    }

    /**
     * 功能描述: 判断活动是否进行中 true:进行中 false: 结束/未开始
     * @Param: [productId]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2022/12/1 17:34
     */
    @Override
    public Boolean getActivityIsUnderwayByProductId(Integer productId, List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return false;
        }
        //查询商品所属活动id
        StoreProductGroupActivity one = storeProductGroupActivityService.getOne(Wrappers.<StoreProductGroupActivity>lambdaQuery()
                .eq(StoreProductGroupActivity::getProductId, productId)
                .in(StoreProductGroupActivity::getActivityId, ids)
                .groupBy(StoreProductGroupActivity::getProductId)
                .orderByDesc(StoreProductGroupActivity::getId)
                .last("limit 1"));
        if (Objects.isNull(one)){
            return false;
        }
        ChannelGroupBooking activityInfo = this.getById(one.getActivityId());
        if (activityInfo.getActivityTimeType() == 0){
            return true;
        }
        return activityInfo.getActivityEndTime().after(new Date()) && activityInfo.getActivityStartTime().before(new Date());
    }

    /**
     * 功能描述: 返回当前商户下进行中活动id
     * @Param: [merId]
     * @Return: java.util.List<java.lang.Integer>
     * @Author: wangzh
     * @Date: 2022/12/2 11:17
     */
    @Override
    public List<Integer> getInProgressActivityIds(Integer merId) {
        List<ChannelGroupBooking> list = this.list(Wrappers.<ChannelGroupBooking>lambdaQuery()
                .eq(ChannelGroupBooking::getMerId, merId)
                .and(e -> e.eq(ChannelGroupBooking::getActivityTimeType, 0)
                        .isNull(ChannelGroupBooking::getActivityEndTime)
                        .or(i -> i.eq(ChannelGroupBooking::getActivityTimeType, 1)
                        .lt(ChannelGroupBooking::getActivityStartTime, new Date())
                        .gt(ChannelGroupBooking::getActivityEndTime, new Date()))));
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        return list.stream().map(ChannelGroupBooking::getId).collect(Collectors.toList());
    }

    /**
     * 功能描述: 返回当前商户下进行中活动id
     * @Param: [merId]
     * @Return: java.util.List<java.lang.Integer>
     * @Author: wangzh
     * @Date: 2022/12/2 11:17
     */
    @Override
    public List<Integer> getInProgressActivityIdsAndLeaderId(Integer merId,Integer leaderId) {
        if(leaderId == null || leaderId == 0) {
            return null;
        }
        List<ChannelGroupBooking> list = this.list(Wrappers.<ChannelGroupBooking>lambdaQuery()
                .eq(ChannelGroupBooking::getMerId, merId)
                .eq(ChannelGroupBooking::getLeaderId, leaderId)
                .and(e -> e.eq(ChannelGroupBooking::getActivityTimeType, 0)
                        .isNull(ChannelGroupBooking::getActivityEndTime)
                        .or(i -> i.eq(ChannelGroupBooking::getActivityTimeType, 1)
                                .lt(ChannelGroupBooking::getActivityStartTime, new Date())
                                .gt(ChannelGroupBooking::getActivityEndTime, new Date()))));

        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        return list.stream().map(ChannelGroupBooking::getId).collect(Collectors.toList());
    }

    /**
     * 功能描述: 获取当前商户下活动id
     * @Param: [merId]
     * @Return: java.util.List<java.lang.Integer>
     * @Author: wangzh
     * @Date: 2022/12/14 14:56
     */
    public List<Integer> getActivityIds(Integer merId){
        List<ChannelGroupBooking> list = this.list(Wrappers.<ChannelGroupBooking>lambdaQuery()
                .eq(ChannelGroupBooking::getMerId, merId));
        if (CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        return list.stream().map(ChannelGroupBooking::getId).collect(Collectors.toList());
    }

    /**
     * 功能描述: 根据团长id获取团长参与的拼团活动商品id
     * @param leaderId
     * @return
     */
    public List<ChannelGroupBookingResponse> getProductByLeaderId(Integer leaderId){
        // 获取活动id
        List<ChannelGroupBooking> groupBookingList = this.lambdaQuery().eq(ChannelGroupBooking::getLeaderId, leaderId).list();

        List<ChannelGroupBookingResponse> groupList = new ArrayList<>();

        /*
        List<Integer> activityIdList = groupBookingList.stream().map(ChannelGroupBooking::getId).distinct().collect(Collectors.toList());
        LambdaQueryWrapper<StoreProductGroupActivity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(StoreProductGroupActivity::getActivityId, activityIdList);
        lambdaQueryWrapper.select(StoreProductGroupActivity::getActivityId, StoreProductGroupActivity::getProductId, StoreProductGroupActivity::getId);
        lambdaQueryWrapper.groupBy(StoreProductGroupActivity::getActivityId);
        List<StoreProductGroupActivity> groupActivityList = storeProductGroupActivityService.list(lambdaQueryWrapper);

        List<Integer> productIdList = groupActivityList.stream().map(StoreProductGroupActivity::getProductId).distinct().collect(Collectors.toList());

        IndexStoreProductSearchRequest searchRequest = new IndexStoreProductSearchRequest();
        searchRequest.setProductIdList(productIdList);

        PageParamRequest pageParamRequest = new PageParamRequest();
        // 
        pageParamRequest.setLimit(productIdList.size());
        List<ProductResponse> productResponseList = productService.getProductList(searchRequest, pageParamRequest, null);
        Map<Integer, ProductResponse> productResponseMap = productResponseList.stream().collect(Collectors.toMap(ProductResponse::getId, Function.identity(), (v1, v2) -> v2));
        */
        for(ChannelGroupBooking group : groupBookingList){
            ChannelGroupBookingResponse groupBooking = new ChannelGroupBookingResponse();
            BeanUtils.copyProperties(group, groupBooking);

            // 根据活动id获取商品id
            StoreProductGroupActivity productGroup = storeProductGroupActivityService.lambdaQuery()
                    .eq(StoreProductGroupActivity::getActivityId, group.getId())
                    .ge(StoreProductGroupActivity::getStock,1)
                    .groupBy(StoreProductGroupActivity::getActivityId).one();
            if(productGroup == null){
                productGroup = storeProductGroupActivityService.lambdaQuery()
                        .eq(StoreProductGroupActivity::getActivityId, group.getId())
                        .groupBy(StoreProductGroupActivity::getActivityId).one();
            }

            StoreProduct product = storeProductService.getById(productGroup.getProductId());

            /*if(product == null){
                continue;
            }*/
            String image = productDescriptionService.lambdaQuery()
                    .eq(StoreProductDescription::getProductId, productGroup.getProductId()).one().getImage();


            /*BigDecimal oldPrice = BigDecimal.ZERO;
            if(null != product.getOldPrice()){
                oldPrice = oldPrice.add(product.getOldPrice());
            }
            if(null != product.getTaxAndSecondPrice()){
                oldPrice = oldPrice.add(product.getTaxAndSecondPrice());
            }*/
            groupBooking.setActivityName(group.getActivityName())
                    .setProductId(product.getId())
                    .setProductName(product.getStoreName())
                    .setProductImage(image)
                    .setProductBrand(product.getBrandName())
                    .setStock(productGroup.getStock())
                    .setPackagePrice(productGroup.getPackagePrice())
                    // .setPrice(oldPrice)
                    // .setTotalTaxPrice(product.getTaxAndSecondPrice())
                    .setRebateRate(group.getRebateRate());

            setBookingStatus(group, groupBooking);

            // 获取团长头像
            String avatar = userService.getById(group.getLeaderId()).getAvatar();
            groupBooking.setAvatar(avatar);

            // 封装到map
            groupList.add(groupBooking);
        }

        return groupList;
    }

    /**
     * 功能描述: 通过活动id获取商品id
     * @Param: [id]
     * @Return: java.lang.Integer
     * @Author: wangzh
     * @Date: 2022/11/29 14:50
     */
    @Override
    public Integer getLeaderIdByActivityId(Integer id) {
        ChannelGroupBooking one = this.getOne(Wrappers.<ChannelGroupBooking>lambdaQuery()
                .eq(ChannelGroupBooking::getId, id)
                .last("limit 1"));
        return one.getLeaderId();
    }
}
